// @Author EthanScriptOn
// @Desc
package actuator

import (
	"gitee.com/fatzeng/srf_switch_basic_components/common/proxy"
)

type LoopBridgeExecutor struct {
	*BridgeExecutor
}

func GenerateLoopBridgeExecutor() *LoopBridgeExecutor {
	instance := new(LoopBridgeExecutor)
	instance.bridgeExecutorProxy = proxy.ProxyTarget(instance)
	return instance
}

func (l *LoopBridgeExecutor) ExecuteSingle(ctx *SrfSwitchBridgeActuatorContext) (err error) {
	config := ctx.BridgeConfig
	recordHolder := ctx.GetRecordHolder()
	defer l.Record(recordHolder, &err)
	structureParam, err := l.StructureParam(ctx, config)
	if err != nil {
		return err
	}
	operatorExecuteCall := l.GetProxy().Call(BridgeExecutor.OperatorExecute, ctx, config, structureParam)
	if err = operatorExecuteCall.GetError(); err != nil {
		return err
	}
	executeRes, _ := operatorExecuteCall.GetResultByType(interface{}(nil))
	responseChan := executeRes.(chan interface{})
	for {
		select {
		case resp, ok := <-responseChan:
			if !ok {
				_ = ctx.Record(OperatorExecute, "responseChan is closed")
				return
			} else {
				resultParseCall := l.GetProxy().Call(BridgeExecutor.ResultParse, config, resp)
				if err = resultParseCall.GetError(); err != nil {
					return err
				}
				parserResult, _ := resultParseCall.GetResultByType(interface{}(nil))
				if err = l.GetProxy().Call(BridgeExecutor.BridgeCollectResult, ctx, config, parserResult).GetError(); err != nil {
					return err
				}
			}
		}
	}
}
